/*
* GeoVISTA Center (Penn State, Dept. of Geography)
* Copyright (c), 2003-2011,  Jin Chen and Alan M. MacEachren, GeoVISTA Center, Penn State University
* All Rights Researved.
* This library is developed and distributed for free usage,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* You can redistribute and/or modify it under the terms of the
* Simplified BSD License
*
*
* 
*
*
*
*
* @Original Author: jin Chen
* @date: Oct 23, 2003$
* @version: 1.0
*/
package edu.psu.geovista.app.dataloader.v1;

import edu.psu.geovista.app.dataloader.v1.actions.ActionManager;
import edu.psu.geovista.app.dataloader.v1.actions.BasicAction;
import edu.psu.geovista.app.dataloader.v1.actions.WizardData;
import edu.psu.geovista.app.dataloader.v1.components.DefaultNCIDataSource;
import edu.psu.geovista.app.dataloader.v1.components.PcpDataLoader;
import edu.psu.geovista.app.dataloader.v1.components.SingleDataLoader;
import edu.psu.geovista.app.dataloader.v1.components.TsDataLoader;
import edu.psu.geovista.app.dataloader.v1.config.model.*;
import edu.psu.geovista.app.dataloader.v1.gui.*;
import edu.psu.geovista.app.dataloader.v1.session.ProjectBuilder;
import edu.psu.geovista.app.vit.pub.utils.VitUtils;
import edu.psu.geovista.common.awt.event.dataloading.*;
import edu.psu.geovista.common.debug.Debug;
import edu.psu.geovista.common.utils.TimeUtils;
import edu.psu.geovista.common.utils.collection.CollectionUtils;
import edu.psu.geovista.ui.dataloader.common.ConfigurePropSavor;
import edu.psu.geovista.ui.event.DataSetEvent;
import edu.psu.geovista.ui.event.DataSetListener;
import epoviz.trex.common.swing.components.progressbar.LongTask;
import epoviz.trex.common.swing.components.progressbar.SwingWorker;
import epoviz.trex.common.swing.components.progressbar.TimerProgressBar;

import javax.swing.*;
import static javax.swing.JOptionPane.ERROR_MESSAGE;
import javax.swing.event.EventListenerList;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Properties;

//import test.edu.psu.geovista.common.swing.model.JSwingTestUtils;


////edu.psu.geovista.ui.dataloader.DataLoaders
//edu.psu.geovista.app.pcp.dataloader.DataLoaders
public class DataLoaders extends JPanel implements Serializable,InternalFrameListener {

    public static final boolean DEBUG=true;

    public static final int Dlg_W=600;
    public static final int Dlg_H=300;
    public static final int Btn_R=1;
    public static final int Btn_M=2;
    public static final int Btn_L=3;

    public static final Color COLOR_SECTION_TITLE=new java.awt.Color(71, 75, 140);
    public static final Font FONT_PAGE_TITLE = new Font("MS Sans Serif", 1, 13);
    public static final Font FONT_SECTION_TITLE = new Font("MS Sans Serif", 1, 12);

    public static final Dimension d1=new Dimension(400,(int)Math.round(400/1.618));
    public static final Dimension d2=new Dimension(Dlg_W,(int)Math.round(Dlg_W/1.414));
    public static final Dimension d3=new Dimension((int)(1.5*Dlg_W),(int)Math.round(1.5*Dlg_W/1.414));


    static final long serialVersionUID = 3709361576650269316L;
    protected ProjectBuilder projBd;// 
    //independent components to load data
    protected PcpDataLoader pcpload;
    protected TsDataLoader tsload;

    //toolkits to load data from files
    protected DefaultNCIDataSource pcpDataSource;
    protected DefaultNCIDataSource tsDataSource;
    protected JInternalFrame container;
    protected Window rootWindow; //  
    //GUI for loading data interactively
    //ProjectNamePane projp;
    protected AskProjectTypePane askPtPane;
    protected AskProjectNamePane askPnPane;
    protected ProjectNameListPane projectNameListPane;
    protected PathsPane pathPane;
    protected AttributesPane attrsPane;
    protected ChooseDataPane chooseDataPane;
    //JPanel pathPane;
    //JPanel pathControlPane; //contain buttons that controll the pathPane
    protected JDialog dialog; // 
    //JDialog projectDialog;


    protected ActionManager actmgr;
    protected WizardData wizardData =new WizardData();


    // 
    //  
    protected String currentProjectName="";

    //boolean needShowPathPane=true;
    //DefaultNCIDataSource dataSource;

    protected EventListenerList listenerList = new EventListenerList();



    public DataLoaders() {
        //dataSource=new DefaultNCIDataSource();
        init();
        JButton loadBttn=new JButton("Load Data");
        loadBttn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                startWizard();
            }

        });
        this.add(loadBttn);

    }
    private void init(){
        this.actmgr=new ActionManager(this);

        pcpDataSource = new DefaultNCIDataSource();
        tsDataSource = new DefaultNCIDataSource();
        pcpDataSource.addPropertyChangeListener(tsDataSource) ;
        tsDataSource.addPropertyChangeListener(pcpDataSource);
        //Two loader must use single propertySavor
        ConfigurePropSavor propertySavor=new ConfigurePropSavor("/.VitPub/config/","dataFiles.cfg");
        this.pcpload =new edu.psu.geovista.app.dataloader.v1.components.PcpDataLoader(pcpDataSource);
        this.tsload =new TsDataLoader(tsDataSource);
        pcpload.setPropertySavor(propertySavor);
        tsload.setPropertySavor(propertySavor);
        Properties props=System.getProperties() ;
        String pcphome=props.getProperty("PCP_HOME");
        if(pcphome!=null ){
            File pcp=(new File(pcphome));
            if(pcp.exists() &&pcp.isDirectory() ){
                pcpload.setRoot(pcp);
                tsload.setRoot(pcp);
            }
        }

        PropertyChangeListener OpenfileListener=new PropertyChangeListener() {  // 
            public void propertyChange(PropertyChangeEvent evt) {
                 String pn=evt.getPropertyName() ;

                if(pn.equals(epoviz.trex.common.swing.components.filechooser.SingleFileSource.FileChooser_Root ) ){
                    File file=(File) evt.getNewValue() ;
                    pcpload.setRoot(file);
                    tsload.setRoot(file);
                }
            }
        };
        pcpload.addFileOpenListener(OpenfileListener);
        tsload.addFileOpenListener(OpenfileListener);

        this.setPreferredSize(new Dimension(400,200)) ;


    }

    public void reset() {
        this.actmgr.setAllEnable();
    }
    /*******************************************************************************************************
     *                service
     *******************************************************************************************************/
  /*  public void loadFiles(String datafile,String metaFile,String shpFile) throws Exception {
        this.pcpDataSource.loadFiles(datafile,metaFile,shpFile);
        this.pcpload.l
    }*/
    /*******************************************************************************************************
     *                GUI
     *******************************************************************************************************/
    public void startWizard(){
        Window  w;
        Window rootw = this.getRootWindow();
        if(rootw!=null){
            w=rootw;
        }
        else{
            w=SwingUtilities.getWindowAncestor(this);
        }
        try {
            VitUtils.showWaitCursor(w,null);

            reset();//to make all actions enable
            this.loadProjectInfo();
            this.showAskProjectTypeDlg(); // 
        }
        catch (IOException e) {
            String s="Unable to load project information.";
                JOptionPane.showMessageDialog(DataLoaders.this,s,"Error",ERROR_MESSAGE);
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        finally {
            //w.setCursor(null);// 
            VitUtils.showNormalCursor(w);
        }


    }



    /**************************************************
     *                project list dialog
     ***************************************************/


    public AskProjectTypePane getAskProjPane(){
        if (this.askPtPane==null) {
            AskProjectTypePane p=new AskProjectTypePane(this);
            //p.setAction(this.getAction(ActionManager.Act_ProjectTypeOk) );
            p.setButtonAction(DataLoaders.Btn_L,this.getAction(ActionManager.Act_CloseDialog),"Cancel");
            p.setButtonAction(DataLoaders.Btn_R,this.getAction(ActionManager.Act_ProjectTypeOk) ,"Next >" ); //"OK"


            askPtPane=p;

        }

        /*if(wizard.getProjectClone().getID().equals(ProjectBuilder.Project_New)){//no project has been loaded*/
        if(isValidString(this.getCurrentProjectName() ) ){

            askPtPane.setCurrentProjectEnable(true); // 
        }
        else{
            askPtPane.setCurrentProjectEnable(false);
        }
        return askPtPane;

    }
      public static boolean isValidString(String s) {
        if(s!=null&&s.length() >0)
            return true;
        else
            return false;
    }
    public ProjectPane getProjectPane() {
        ProjectPane p=null;
        if(wizardData.getProjectCategory()== WizardData.New ){
            p= getAskPnPane();
        }
        else /*if(wizard.getProjectCategory()==Wizard.Exist)*/{

            ProjectNameListPane pl = getProjectNameListPane();

            /*  
            NOT put here, put in showProjectDlg. This method will be invoked after you select a project
            String [] pnames=this.getProjectNameList();
            String n=pl.getSelectedProjectName() ;
            pl.setProjectNames(pnames);
            p=pl;*/

            /*pl.setProjectNames(pnames);  */
            p=pl;
        }
        return p;
    }
    public  AskProjectNamePane getAskPnPane(){
        if(this.askPnPane ==null){
            AskProjectNamePane p =new AskProjectNamePane(this);
            p.setButtonAction(Btn_L,this.getAction(ActionManager.Act_ShowProjType),"< Back");
            p.setButtonAction(Btn_R,this.getAction(ActionManager.Act_ShowChooseData),"Next >" );

            askPnPane=p;
        }
        //projectPane.setPreferredSize(new Dimension(300,200));
        return askPnPane;
    }
    // 
    public  ProjectNameListPane getProjectNameListPane(){
        if(this.projectNameListPane ==null){
            ProjectNameListPane p =new ProjectNameListPane(this);
            p.setButtonAction(Btn_L,this.getAction(ActionManager.Act_ShowProjType),"< Back");
            p.setButtonAction(Btn_M,this.getAction(ActionManager.Act_ShowChooseData),"Next >" );
            p.setButtonAction(Btn_R,this.getAction(ActionManager.Act_QuickLoad),"Finish");

            projectNameListPane=p;
        }
        //projectPane.setPreferredSize(new Dimension(300,200));
        return projectNameListPane;
    }



    private String [] getProjectNameList(){
        java.util.List ids=projBd.getSortedProjectIDs();//0416 getConfiguror().getSortedProjectIDs();

        String [] names=CollectionUtils.convert2StringArrayNoNull(ids);
        return names;
    }


    public ChooseDataPane getChooseDataPane() {
        BasicAction autoloadAction = this.getAction(ActionManager.Act_AutoChooseLoad);
        if (this.chooseDataPane==null) {
            //JPanel p=new JPanel();
            ChooseDataPane p=new ChooseDataPane(this);
            p.setButtonAction(Btn_L,this.getAction(ActionManager.Act_BackChooseData),"< Back");
            p.setButtonAction(Btn_M,this.getAction(ActionManager.Act_SetPath),"Next >" );

            p.setButtonAction(Btn_R,autoloadAction,"Finish");

            chooseDataPane=p;

        }
        int pctg = this.wizardData.getProjectCategory();
        if(pctg== WizardData.New){//new project, disable Finish button since it has no path yet
            autoloadAction.setEnabled(false);
        }
        else{//existing project
            autoloadAction.setEnabled(true);

        }
        return  chooseDataPane;

    }
    public PathsPane getPathsPane() {
        System.out.println("getPathsPane()");
        if (this.pathPane==null) {
            //JPanel p=new JPanel();
            PathsPane p=new PathsPane(this);
            p.setButtonAction(Btn_L,this.getAction(ActionManager.Act_ShowChooseData),"Back<");
            p.setButtonAction(Btn_M,this.getAction(ActionManager.Act_SelectAttrs),"Next>" );
            BasicAction autoloadAction = this.getAction(ActionManager.Act_AutoSelectLoad);
            //autoloadAction.setEnabled(true);
            p.setButtonAction(Btn_R,autoloadAction,"Finish");
            pathPane=p;

        }
        if(this.wizardData.isLoadPcpdata()&&this.wizardData.isLoadTsdata()){
            pathPane.showPcpTs();
        }
        else if(this.wizardData.isLoadPcpdata()&&!this.wizardData.isLoadTsdata()){
            pathPane.showPcpOnly();
        }
        else if(!this.wizardData.isLoadPcpdata()&&this.wizardData.isLoadTsdata()){
            pathPane.showTsOnly();
        }
        return  pathPane;

    }
    public AttributesPane getAttrsPane() {

        if (this.attrsPane==null) {
            //JPanel p=new JPanel();
            AttributesPane p=new AttributesPane(this);
            p.setButtonAction(Btn_L,this.getAction(ActionManager.Act_SetPath),"Back<");
            //p.setButtonAction(Btn_M,this.getAction(ActionManager.Act_SelectAttrs),"Next>" );
            p.setButtonAction(Btn_R,this.getAction(ActionManager.Act_FinalLoad),"Finish");
            attrsPane=p;

        }
        if(this.wizardData.isLoadPcpdata()&&this.wizardData.isLoadTsdata()){
            attrsPane.showPcpTs();
        }
        else if(this.wizardData.isLoadPcpdata()&&!this.wizardData.isLoadTsdata()){
            attrsPane.showPcpOnly();
        }
        else if(!this.wizardData.isLoadPcpdata()&&this.wizardData.isLoadTsdata()){
            attrsPane.showTsOnly();
        }

        return  attrsPane;

    }




    /**************************************************
     *                show paths dialog
     ***************************************************/

    public void showAskProjectTypeDlg(){

        this.showPaneInDlg(getAskProjPane(),d1,"Data Wizard");

    }
    //used by NciPcpApp to load project pane
    public void showProjectDlg() {
        ProjectPane p=this.getProjectPane();
        this.showPaneInDlg(p,d1,"Data Wizard");
        //ProjectNameListPane projectPane = this.getProjectNameListPane();
        if(this.wizardData.getProjectCategory()== WizardData.New ){  //a new project

        }
        else{ //existing project
            ProjectNameListPane projectPane = (ProjectNameListPane) p;


            String [] pnames=this.getProjectNameList();

            projectPane.setProjectNames(pnames);


        }
        this.showPaneInDlg(p,d1,"Data Wizard");


    }
    public void showChooseDataDlg() {
        showPaneInDlg(getChooseDataPane(),d1,"Data Wizard");
    }
    public void showPathDlg(){

        PathsPane p=this.getPathsPane();
        this.showPaneInDlg(p,d2,"Data Wizard");

    }

    /**
     *
     */
    public void showAttributesDlg(){

        AttributesPane p=this.getAttrsPane() ;
        p.deselectAllAttributes();

        this.showPaneInDlg(p,d3,"Select Data for Analysis");

    }
    /**
     * show a JPanel in a Dialog
     * @param pane
     */
    public  void showPaneInDlg(JPanel pane,Dimension d,String title){
        final JDialog dlg=this.getDialog() ;
        if(d!=null){
            dlg.setSize(d);
        }
        if(title!=null){
            dlg.setTitle(title);
        }
        //dlg.setMainPanel(pane);
        //Container contentPane = dlg.getco
        Container contentPane = dlg.getContentPane();
        contentPane.removeAll() ;
        contentPane.add(pane );
        contentPane.invalidate();
        contentPane.repaint() ;
        // 
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                dlg.show();  // 
            }
        });
        //dlg.show();  // 
        //dlg.requestFocus();
        //dlg.dispose() ;
    }
    /**
     * simply return a empty dialog
     * @return
     */
    public   JDialog getDialog() {

        if(dialog==null){
            JDialog dlg=new JOptionPane().createDialog(this,"Data Loader");
            //DynamicDialog dlg=new DynamicDialog();
            dlg.setTitle("Data Loader") ;
            dlg.setModal(true);
            dlg.getContentPane().removeAll() ;
            dlg.setResizable(true);
            dlg.setSize(new Dimension(Dlg_W,Dlg_H));
            Dimension d=Toolkit.getDefaultToolkit().getScreenSize();

            dlg.setLocation(d.width/2-Dlg_W/2,d.height/2-Dlg_H/2);
            dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE );
            // return dlg;
            dlg.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent we) {
                    //if(DEBUG)
                    //   System.out.println("---------------------------close dialog");
                    //In case user did not click save button, but simply close the windows, it still save the data
                    //Not save
                    /* try {
                    saveSessionPath();
                    } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }  */
                    cleanDataSource();
                    disposeDialog();
                }
            });
            dialog=dlg;
        }

        return dialog;
    }
    public void disposeDialog(){
        if(dialog!=null)
            dialog.dispose() ;
    }
    /*******************************************************************************************************
     *                support
     *******************************************************************************************************/
    /**************************************************
     *                load project info
     ***************************************************/

    public void loadProjectInfo() throws IOException {
        if(projBd==null)
            this.projBd =new ProjectBuilder();
        projBd.loadProjectInfo();
    }
    public void cleanProjectInfo() {
        this.projBd=null;
    }
    /**
     *  
     * @return  true if success
     * @param project
     */
    public boolean setDataInfo(Project project){
        // 
        this.cleanDataSource() ;

        if(true/*wizard.getProjectCategory()!=Wizard.New */){ //existing projects
            Pcpdata pcpdata = project.getPcpdata();
            boolean loadpcp=pcpdata.isLoad();
            TimeSeriesData tsdata = project.getTsdata();
            boolean loadts=tsdata.isLoad();
            if(loadpcp){
                pcpload.setDataInfo(pcpdata );
            }
            if(loadts){
                tsload.setDataInfo(tsdata);
                //tsload.setDataInfo(tsdata);
            }
            //projBd.setCurrPj(project);

            // this.actmgr.setEnable(ActionManager.Act_QuickLoad,true);
        }
        else{// 
            // 
            pcpload.reset() ;//setDataInfo(null ); // 
            tsload.reset() ;//setDataInfo(null);

        }
        return true;

    }
    /**
     *
     * @return  true if success
     */
    public boolean autoSelectAttributes() {
        boolean pcploadOk=false ;
        boolean tsloadOk=false ;
        /*try {
        this.saveProjectInfo() ;
        } catch (IOException e) {
        if(DEBUG)
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }*/

        String expMsg=null;//exception msg
        try {

            if (this.wizardData.isLoadPcpdata() ) {
                pcploadOk = this.autoSelectAttrs(pcpload);//this.pcpload.autoSelectAttributes();
            }
            else{
                pcploadOk=true;
            }

            //loadts = this.tsload.autoSelectAttributes();
        } catch (Exception e) {
            String es = e.getMessage();
            expMsg= (es==null)?"":es;
            if(DEBUG)
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        try {
            //loadpcp = this.pcpload.autoSelectAttributes();
            if (this.wizardData.isLoadTsdata()) {
                tsloadOk = this.autoSelectAttrs(tsload);//this.tsload.autoSelectAttributes();
            } else {
                tsloadOk=true;
            }
        } catch (Exception e) {
            String es = e.getMessage();
            expMsg= (es==null)?"":es;
            if(DEBUG)
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

        }
        String checkpath="please check path marked with red symbol.";
        String pcpfail=" Fail to load pcp data,"+checkpath;
        String tsfail=" Fail to load time series data,"+checkpath;
        StringBuffer errMsg=new StringBuffer();//A general msg
        if(pcploadOk==false){
            errMsg.append( pcpfail+"\n");
        }
        if(tsloadOk==false){
            errMsg.append(tsfail+"\n");
        }
        if(expMsg!=null){
            errMsg.append(expMsg+"\n");
        }

        if(errMsg.toString() !=null&&errMsg.toString().length() >0)  {
            int n=this.askIfTryGain(errMsg.toString() );
            if(n==JOptionPane.YES_OPTION){
                showPathDlg();
            }
            else if(n==JOptionPane.NO_OPTION ){
                this.showAttributesDlg();
            }
            // Debug.displayError(this ,errMsg);

            return false;
        }
        else{
            return true     ;
        }
    }

    private boolean autoSelectAttrs(SingleDataLoader loader)throws Exception {

        //3. load data, if path not correct =>exception

        boolean success=loader.loadDataInfo();
        //4. if data is loaded, selected attributes
        if(success){
            if(wizardData.getProjectCategory()== WizardData.New){
                loader.selectAllAttributes();
                return true;
            }
            else{//a exsiting/current project
                Project project = wizardData.getProjectClone();
                VariableData datainfo=null;
                if(loader instanceof PcpDataLoader){
                    datainfo=project.getPcpdata();
                }
                else if (loader instanceof TsDataLoader){
                    datainfo=project.getTsdata() ;
                }

                String [] attrs=new String[0];
                if(datainfo!=null){
                    attrs=ModelUtils.getSelectAttributeNames(datainfo);
                }
                if(attrs!=null&&attrs.length >0){
                    loader.selectAttributes(attrs) ;

                }
                else{
                    loader.selectAllAttributes();

                }
                return success;
            }

        }
        else{
            return false;
        }

    }
    private int askIfTryGain(String errmsg){
        String msg=errmsg+"\n";

        Object [] opts=new Object[]{
            "Set paths,try again","Skip loading the data"
        };
        int n  =JOptionPane.showOptionDialog(this,msg,"Choose",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE ,null,opts,opts[0]);
        return n;

    }
    public  void saveProjectInfo() throws IOException {
        //1. set current project
        Project currentproject=this.wizardData.getProjectClone();
        /*boolean loadpcp=currentproject.getPcpdata().isLoad();
        boolean loadts=currentproject.getTsdata().isLoad();
        if(loadpcp)
        pcpload.fillProjectInfo(currentproject.getPcpdata() );
        if(loadts)
        tsload.fillProjectInfo(currentproject.getTsdata() );*/
        currentproject.setTime(TimeUtils.getCurrentTimeString());
        if(projBd!=null){
         projBd.updateProject(currentproject);

        //2. update Last project
        /*ProjectType lastp=this.projBd.getConfiguror().getProjectByID(ProjectBuilder.Project_LastOne );
        lastp.setTime(TimeUtil.getCurrentTimeString());
        ConfigureProcessor.copyProperties(currentproject,lastp);*/

        //3. save all
        try {
            projBd.save();
            // this.dataloader.cleanDataSource();
            //pathDialog.dispose() ;
        } catch (IOException e1) {
            //todo
            Debug.displayError(this,"Unable to save project setting! ");
            e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        }

    }
    /**
     * 1. Save project
     * 2. load data
     */
    /*public void loadFinalData(){
    boolean closeDlg=true;
    //String projname=this.projBd.getCurrPj().getID();
    try {

    saveProjectInfo() ;
    } catch (IOException e) {
    closeDlg=false;
    //todo show a dialog, asking if disposeDialog

    if(DEBUG)
    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
    try {
    this.uponLoadingData();

    if(this.wizard.isLoadPcpdata()){
    this.pcpload.doApply() ;
    }
    if(this.wizard.isLoadTsdata()){
    this.tsload.doApply() ;
    }

    this.cleanDataSource() ;//to reclaim memory
    this.cleanProjectInfo();
    //this.setCurrentProjectName(projname);  // 
    if(closeDlg)
    this.disposeDialog();
    } catch (Exception e) {
    JOptionPane.showMessageDialog(this,e.getMessage() );
    this.showAttributesDlg();
    if(DEBUG)
    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

    }*/

    public void loadFinalData(){
        // 
        class LoadDataTask extends LongTask{
            //protected TimerProgressBar progressbar;

            protected  void showDilaog(SwingWorker worker) {

                progressbar=new TimerProgressBar(5){
                    public int showDialog(Component c,String message){
                        int value=0;//c,message,"",new String [0]{});
                        try {
                            value = this.showDialog(c,message,"",new String[0]);
                        } catch (Exception e) { //for some reason, it may throw .ArrayIndexOutOfBoundsException
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }
                        return value;
                    }
                };
                int value= progressbar.showDialog(DataLoaders.this,"One moment while your data is loaded ...");    //Please wait loading data
                if(value==JOptionPane.YES_OPTION   // 
                        ||value==JOptionPane.CLOSED_OPTION ){
                    //  
                }
            }
            public void updateUI(){
                 progressbar.setDone(true);
                progressbar.disposeDialog();
                System.out.println("Update GUI");
            }
            public Object doActualTask() {
                boolean closeDlg=true;
                //String projname=projBd.getpgetCurrPj().getID();
                try {

                    saveProjectInfo() ;
                } catch (IOException e) {
                    closeDlg=false;
                    //todo show a dialog, asking if disposeDialog

                    if(DEBUG)
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
                try {
                    DataLoaders.this.beforeLoadingData();
                    String projId = wizardData.getProjectID();
                    if( DataLoaders.this.wizardData.isLoadPcpdata()){
                        DataLoaders.this.pcpload.doApply() ;
                    }
                    if( DataLoaders.this.wizardData.isLoadTsdata()){
                        DataLoaders.this.tsload.doApply() ;
                    }

                    DataLoaders.this.cleanDataSource() ;//to reclaim memory
                    DataLoaders.this.cleanProjectInfo();
                    //this.setCurrentProjectName(projname);  // 

                    afterLoadingData(projId) ;
                    if(closeDlg)
                        DataLoaders.this.disposeDialog();
                } catch (Exception e) {
                    this.progressbar.disposeDialog();
                    JOptionPane.showMessageDialog( DataLoaders.this,e.getMessage() );
                    DataLoaders.this.showAttributesDlg();
                    if(DEBUG)
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
                if(progressbar!=null)
                    this.progressbar.disposeDialog();
                return null;
            }
        }

        LoadDataTask task=new LoadDataTask();
        task.start();

    }




    public  void cleanDataSource(){
        if(pcpDataSource!=null)pcpDataSource.cleanData() ;
        if(tsDataSource!=null)tsDataSource.cleanData() ;
    }


    public void tsChange(TSEvent e) {
    }
    public void dataSetChanged(DataSetEvent e) {
    }
    /*******************************************************************************************************
     *                 event
     *******************************************************************************************************/
    public void addDataSetListener(DataSetListener l) {
        pcpload.addDataChangeListener( l);
    }

    /**
     * removes an DataSetListener from the button
     */
    public void removeDataSetListener(DataSetListener l) {
        pcpload.removeDataChangeListener(l);
    }
    /**
     * time series evnt
     */
    /**
     * implements TsDataListener
     */
    public void addTsDataListener(TSDataListener l) {
        tsload.addTsDataListener(l);
    }
    public void removeTsDataListener(TSDataListener l) {
        tsload.removeTsDataListener(l);
    }
    /**
     * To close the frame, dataloader must know its container
     * @param container
     */
    public void setContainer(JInternalFrame container) {
        this.container = container;
    }

    public void addBeforeLoadingListener(BeforeLoadingListener l) {
        this.listenerList.add(BeforeLoadingListener.class, l)    ;
    }
    public void removeBeforeLoadingListener(BeforeLoadingListener l) {
        this.listenerList.remove(BeforeLoadingListener.class, l)    ;
    }
    public void beforeLoadingData() {
        Object[] listeners=this.listenerList.getListenerList() ;
        BeforeLoadingEvent e=null;
        for (int i=listeners.length -2;i>=0;i-=2){
            if (listeners[i]== BeforeLoadingListener.class){
                e=new BeforeLoadingEvent(this);
                e.setLoadPcpData(this.wizardData.isLoadPcpdata());
                e.setLoadTsData(this.wizardData.isLoadTsdata());
               ((BeforeLoadingListener)listeners[i+1]).processBeforeLoadData(e);
            }


        }
    }

    public void addAfterLoadingListener(AfterLoadingListener l) {
        this.listenerList.add(AfterLoadingListener.class, l)    ;
    }
    public void removeAfterLoadingListener(AfterLoadingListener l) {
        this.listenerList.remove(AfterLoadingListener.class, l)    ;
    }
    /**
     * broadcast data loading process finished
     */
    private  void afterLoadingData(String projId) {
        Object[] listeners=this.listenerList.getListenerList() ;
        AfterLoadingEvent e=null;
        for (int i=listeners.length -2;i>=0;i-=2){
            if (listeners[i]== AfterLoadingListener.class){
                e=new AfterLoadingEvent(this);
                e.setProjectId(projId);
                 ((AfterLoadingListener)listeners[i+1]).processAfterDataLoaded(e);

            }


        }
    }


    /*******************************************************************************************************
     *                consider the component will be put in internalframe
     *******************************************************************************************************/
    public void internalFrameOpened(InternalFrameEvent e) {
    }

    public void internalFrameClosing(InternalFrameEvent e) {
        try {
            this.saveProjectInfo() ;
        } catch (IOException e1) {
            e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void internalFrameClosed(InternalFrameEvent e) {
    }

    public void internalFrameIconified(InternalFrameEvent e) {
    }

    public void internalFrameDeiconified(InternalFrameEvent e) {
    }

    public void internalFrameActivated(InternalFrameEvent e) {
    }

    public void internalFrameDeactivated(InternalFrameEvent e) {
    }

    public PcpDataLoader getPcpload() {
        return pcpload;
    }

    public TsDataLoader getTsload() {
        return tsload;
    }

    public String getCurrentProjectName() {
        return currentProjectName;
    }

    public void setCurrentProjectName(String currentProjectName) {
        this.currentProjectName = currentProjectName;
    }

    public ProjectBuilder getProjBd() {
        return projBd;
    }

    public BasicAction getAction(String name){
        return this.actmgr.getAction(name);
    }

    public WizardData getWizard() {
        return wizardData;
    }

    public void setRootWindow(Window rootWindow) {
        this.rootWindow = rootWindow;
    }

    public   Window getRootWindow() {
        return rootWindow;
    }

    class DynamicDialog extends JDialog{
        JPanel mainp=new JPanel();

        public DynamicDialog() throws HeadlessException {
            Container contentPane = getContentPane();
            contentPane.add(mainp );
        }

        public void setMainPanel(JPanel p) {
            mainp.removeAll();
            mainp.add(p);
            mainp.revalidate() ;
        }

    }
   

}

